/**
* Linkenstein  - Google Chrome extension for advanced hyperlink copying.
* Copyright (C) 2013  Mykola Bespaliuk
*/
/*global document, chrome */
var linkenstein = linkenstein || {}, links, i;

linkenstein.event   = {};

links = document.getElementsByTagName( 'a' );

Array.prototype.map.call(links, function (link) {
    link.addEventListener(
        'mousedown',
        function( event ) {
            linkenstein.event = event;
            setTimeout( function() {
                linkenstein.event = {};
            }, 10000 );
        }
    );
});

linkenstein.keyCode = {};

document.onkeydown = function( event ) {
    linkenstein.keyCode.keyCode = event.keyCode;
};

document.onkeyup   = function() {
    linkenstein.keyCode = {};
};


chrome.extension.onMessage.addListener(
    function( request, sender, sendResponse ) {
        var keyCode = {},
            innerText = {};

        if( linkenstein.event.target != undefined ) {
            innerText.innerText = linkenstein.event.target.innerText;
            if( linkenstein.event.shiftKey === true ) {
                keyCode.keyCode = 16;
            } else if( linkenstein.event.ctrlKey === true ) {
                keyCode.keyCode = 17;
            }
        } else if( linkenstein.keyCode.keyCode != undefined ) {
            keyCode.keyCode = linkenstein.keyCode.keyCode;
        }

        if ( request.request == "getTargetInnerText" ) {
            sendResponse( innerText );
        } else if ( request.request == "getKeyCode" ) {

            sendResponse( keyCode );
        } else {
            sendResponse( {} );
        }
});
